<?php

namespace app\api\controller;

use app\api\model\User as UserModel;
use app\api\service\Sms;
use app\common\model\Region;

/**
 * 用户管理
 * Class User
 * @package app\api
 */
class User extends Controller
{
    /**
     * 用户自动登录
     * @return array
     * @throws \app\common\exception\BaseException
     * @throws \think\Exception
     * @throws \think\exception\DbException
     */
    public function login()
    {
        $model = new UserModel;
        $user_id = $model->login($this->request->post());
        if(!$user_id){
            return $this->renderError('用户名密码错误',null);
        }
        $token = $model->getToken();
        return $this->renderSuccess([
            'user_id' => $user_id,
            'token' => $token
        ]);
    }

    /**
     * 当前用户详情
     * @return array
     * @throws \app\common\exception\BaseException
     * @throws \think\exception\DbException
     */
    public function detail()
    {
        // 当前用户信息
        $userInfo = $this->getUser();
        return $this->renderSuccess(compact('userInfo'));
    }

    /**
     * 注册用户
     * @param $data
     * @param int $referee_id
     * @return mixed
     * @throws \Exception
     * @throws \think\exception\DbException
     */
    public function register()
    {
        $model = new UserModel;
        $prama = $this->request->post();
        $uid = $this->request->param('uid');
        $referee_id = isset($uid)?$uid:null;
        $res = $model->register($prama,$referee_id);
        if($res){
            return $this->renderSuccess(null,'用户注册成功!');
        }else{
            return $this->renderError('用户注册失败');
        }
    }

    /**
     * 发送验证码
     * @return array
     * @throws \app\common\exception\BaseException
     * @throws \think\Exception
     */
    public function sendcode(){
        $type = $this->request->post('type');
        $mobile  = $this->request->post('mobile');
        if(empty($type) || empty($mobile)){
            return $this->renderError('缺失必要参数');
        }
        $sms = new Sms($type,900);
        //生成注册验证码
        $code['code'] = rand(100000,999999);
        if($sms->sendmsg($mobile,$code['code'],$type)){
            return $this->renderSuccess(null,'验证码发送成功!');
        }else{
            return $this->renderError('验证码发送失败');
        }
    }



}
